package com.example.questionnaire.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.questionnaire.common.ResponseCode;
import com.example.questionnaire.dao.*;
import com.example.questionnaire.exception.RException;
import com.example.questionnaire.pojo.DO.*;
import com.example.questionnaire.service.QuestionTitleService;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

@Service
public class QuestionTitleServiceImpl implements QuestionTitleService {

    @Autowired
    private AllQuestionMapper allQuestionMapper;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private DoubleChoiceQuestionMapper doubleChoiceQuestionMapper;

    @Autowired
    private MultipleChoiceQuestionMapper multipleChoiceQuestionMapper;

    @Autowired
    private FillInQuestionMapper fillInQuestionMapper;

    @Autowired
    private ScoreQuestionMapper scoreQuestionMapper;

    @Autowired
    private EvaluateQuestionMapper evaluateQuestionMapper;
    @Autowired
    private OptionsMapper optionsMapper;


    @Override
    public boolean updateAddFillInQuestion(String formid, String title, String subjectId, boolean is_mustAnswer,boolean is_writePrompt, String tipContent, int multilineText, String attribute, boolean is_spaceConstraints, String maxNum, String minNum, boolean is_notAllowedToRepeat, String questionsJumpItems) {
        int questionType = 3;
        QueryWrapper<AllQuestion> wrapperSubjectId = new QueryWrapper<>();
        wrapperSubjectId.eq("subject_id",subjectId);
        if(allQuestionMapper.selectOne(wrapperSubjectId) != null){
            UpdateWrapper<AllQuestion> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("subject_id",subjectId)
                    .set("title",title);
            int wm = allQuestionMapper.update(null, updateWrapper);
            if (wm < 1){
                throw new RuntimeException("插入失败");
            }
//            int i = isMustAnswer ? 1 : 0;
//            int j = isWritePrompt ? 1 : 0;
//            int f = isSpaceConstraints ? 1 : 0;
//            int e = isNotAllowedToRepeat ? 1 : 0;
            UpdateWrapper<FillInQuestion> updateWrapper1 = new UpdateWrapper<>();
            updateWrapper1.eq("subject_id",subjectId)
                    .set("title",title)
                    .set("is_must_answer",is_mustAnswer ? 1 : 0)
                    .set("is_write_prompt",is_writePrompt ? 1 : 0)
                    .set("tip_content",tipContent)
                    .set("attribute",attribute)
                    .set("multiline_text",multilineText)
                    .set("is_not_allowed_to_repeat",is_notAllowedToRepeat ? 1 : 0)
                    .set("is_space_constraints",is_spaceConstraints ? 1 : 0)
                    .set("max_num",maxNum)
                    .set("min_num",minNum)
                    .set("questions_jump_items",questionsJumpItems);
            int k = fillInQuestionMapper.update(null, updateWrapper1);
            if (k < 1){
                throw new RuntimeException("插入失败");
            }
            return false;

        }
        //将题目数量（顺序）储存到对应的问题表和问卷表里面
        QueryWrapper<Questionnaire> wrapper = new QueryWrapper<>();
        wrapper.eq("formid",formid);
        Questionnaire questionnaire = questionnaireMapper.selectOne(wrapper);
        int questionNumber = questionnaire.getQuestionNumber();

        questionNumber++;

        UpdateWrapper<Questionnaire> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("formid", formid)
                .set("question_number", questionNumber);
        int k = questionnaireMapper.update(null, updateWrapper);
        if (k < 1){
            throw new RuntimeException("插入失败");
        }

        //将数据存进所有问题表里
        AllQuestion allQuestion = new AllQuestion();
        allQuestion.setFormid(formid);
        allQuestion.setQuestionType(questionType);
        allQuestion.setSubjectId(subjectId);
        allQuestion.setTitle(title);
        allQuestion.setSubjectNum(questionNumber);

        int i = allQuestionMapper.insert(allQuestion);
        if (i < 1) {
            throw new RuntimeException("插入失败");
        }

        //将数据存进填空题表里面
//        int h = isMustAnswer ? 1 : 0;
//        int a = isWritePrompt ? 1 : 0;
//        int f = isSpaceConstraints ? 1 : 0;
//        int e = isNotAllowedToRepeat ? 1 : 0;
        FillInQuestion fillInQuestion = new FillInQuestion();
        fillInQuestion.setFormid(formid);
        fillInQuestion.setSubjectId(subjectId);
        fillInQuestion.setTitle(title);
        fillInQuestion.setIsMustAnswer(is_mustAnswer ? 1 : 0);
        fillInQuestion.setIsWritePrompt(is_writePrompt ? 1 : 0);
        fillInQuestion.setTipContent(tipContent);
        fillInQuestion.setAttribute(attribute);
        fillInQuestion.setMultilineText(multilineText);
        fillInQuestion.setIsNotAllowedToRepeat(is_notAllowedToRepeat ? 1 : 0);
        fillInQuestion.setIsSpaceConstraints(is_spaceConstraints ? 1 : 0);
        fillInQuestion.setMaxNum(maxNum);
        fillInQuestion.setMinNum(minNum);
        fillInQuestion.setQuestionsJumpItems(questionsJumpItems);

        int j = fillInQuestionMapper.insert(fillInQuestion);
        if (j < 1) {
            throw new RuntimeException("插入失败");
        }

        return true;
    }

    @Override
    public List<AllQuestion> jumpquestiontitle(String subjectId) {
//获取指定问题id对应的题号
        QueryWrapper<AllQuestion> wrapper = new QueryWrapper<>();
        wrapper.eq("subject_id", subjectId);
        wrapper.select("formid", "subject_num");

        AllQuestion a = allQuestionMapper.selectOne(wrapper);

        List<AllQuestion> resultList = new ArrayList<>();
//
//        if (subjectNum != null) {
////            QueryWrapper<AllQuestion> lastQuestionWrapper = new QueryWrapper<>();
////            lastQuestionWrapper.select("subject_num")
////                    .orderByAsc("subject_num")
////                    .last("LIMIT 1");
////            AllQuestion lastQuestion = allQuestionMapper.selectOne(lastQuestionWrapper);
//
////查询大于当前题号的所有问题
        if(a != null) {
        QueryWrapper<AllQuestion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("formid", a.getFormid())
                .gt("subject_num", a.getSubjectNum())
                .orderByAsc("subject_num")
                .select("subject_id", "subject_num", "title");
        resultList = allQuestionMapper.selectList(queryWrapper);
    }
//处理查询结果
// for (AllQuestion question : resultList){
// System.out.println("问题ID: " + question.getsubjectId());
// System.out.println("题号: " + question.getsubjectNum());
// System.out.println("题目: " + question.getQuestionTitle());
// }


                return resultList;

//        }
//        return null;
    }
//    @Override
//    public List<Object> getAllInformation(int subjectId) {
//        List<Object> result = new ArrayList<>();
//        QueryWrapper<Options> wrapper = new QueryWrapper<>();
//        wrapper.eq("subject_id",subjectId);
//        QueryWrapper<FillInQuestion> wrapper1 = new QueryWrapper<>();
//        wrapper1.eq("subject_id",subjectId);
//        if (fillInQuestionMapper.selectOne(wrapper1) == null) {
//            List<Object> options = new ArrayList<>(Collections.singletonList(optionsMapper.selectList(wrapper)));
//            if (doubleChoiceQuestionMapper.selectInformation(subjectId) == null) {
//                options.add(multipleChoiceQuestionMapper.selectInformation(subjectId));
//            } else {
//                options.add(doubleChoiceQuestionMapper.selectInformation(subjectId));
//            }
//            result = options;
//        }
//        else {
//            List<FillInQuestion> fillInQuestions = new ArrayList<>();
//            fillInQuestions.add(fillInQuestionMapper.selectInformation(subjectId));
//            result = Collections.singletonList(fillInQuestions);
//        }
//        return result;
//    }
    @Override
    public List<Object> getallquestions(String formid) {
        List<Object> result = new ArrayList<>();
        QueryWrapper<AllQuestion> wrapper = new QueryWrapper<>();
        wrapper.eq("formid", formid)
                .orderByAsc("subject_num")
                .select("subject_num","subject_id","question_type");
        List<AllQuestion> subjectNum = allQuestionMapper.selectList(wrapper);
        for(AllQuestion i : subjectNum){

            if(fillInQuestionMapper.selectInformation(i.getSubjectId()) != null){
                result.add(fillInQuestionMapper.selectInformation(i.getSubjectId()));
            }
            if(multipleChoiceQuestionMapper.selectInformation(i.getSubjectId()) != null){
                result.add(multipleChoiceQuestionMapper.selectInformation(i.getSubjectId()));
            }
            if(doubleChoiceQuestionMapper.selectInformation(i.getSubjectId()) != null){
                result.add(doubleChoiceQuestionMapper.selectInformation(i.getSubjectId()));
            }
            if(scoreQuestionMapper.selectInformation(i.getSubjectId()) != null){
                result.add(scoreQuestionMapper.selectInformation(i.getSubjectId()));
            }
            if(evaluateQuestionMapper.selectInformation(i.getSubjectId()) != null){
                result.add(evaluateQuestionMapper.selectInformation(i.getSubjectId()));
            }
        }
        for (Object obj : result) {
            System.out.println(obj.toString() + obj.getClass().getSimpleName());
        }
        System.out.println(result);
        return result;
//        QueryWrapper<FillInQuestion> Wrapper = new QueryWrapper<>();
//        Wrapper.eq("formid", formid);
//        result.add(fillInQuestionMapper.selectList(Wrapper));
//        QueryWrapper<DoubleChoiceQuestion> Wrapper1 = new QueryWrapper<>();
//        Wrapper1.eq("formid", formid);
//        result.add(doubleChoiceQuestionMapper.selectList(Wrapper1));
//        QueryWrapper<MultipleChoiceQuestion> Wrapper2 = new QueryWrapper<>();
//        Wrapper2.eq("formid", formid);
//        result.add(multipleChoiceQuestionMapper.selectList(Wrapper2));
//        System.out.println(result);
    }

    // 新增多选题
    @Override
    public boolean updateAddDoubleChoiceQuestion(String formid, String title, String subjectId, boolean isGroup, boolean isSort, boolean isMustAnswer, boolean isWritePrompt, String tipContent, String questionsJumpItems, String numberOfOptions, String optionArray, int most, int mini, String groupingArray) throws IOException {
        int questionType = 2;

        QueryWrapper<Options> wrapper10 = new QueryWrapper<>();//删除选项
        wrapper10.eq("subject_id",subjectId);
        int wmk = optionsMapper.delete(wrapper10);
        if (wmk < 0){
            throw new RuntimeException("插入失败");
        }
        // 将打包的编辑选项转化为map
        ObjectMapper objectMapper = new ObjectMapper();
        // JSON字符串转换成JSON大数组
        JSONArray jsonBigArray = JSON.parseArray(optionArray);
        int count = 0;

        for(int i = 0; i < jsonBigArray.size(); i ++){
            Options options = new Options();

            JSONObject jsonObject = jsonBigArray.getJSONObject(i);
            System.out.println(jsonObject);
            List<Map<String, Object>> map1 = objectMapper.readValue(String.valueOf(jsonObject.get("moreUpdata")), new TypeReference<List<Map<String,Object>>>() {});

            for(Map maps1 : map1){
                if(Integer.parseInt(String.valueOf(maps1.get("value"))) == 0){
                    if (Boolean.parseBoolean(String.valueOf(maps1.get("checked")))){
                        options.setIsScoring(1);
                    }else { options.setIsScoring(0);}
                }
                if(Integer.parseInt(String.valueOf(maps1.get("value"))) == 1){
                    if (Boolean.parseBoolean(String.valueOf(maps1.get("checked")))){
                        options.setFillIn(1);
                    }else { options.setFillIn(0);}
                }
                if(Integer.parseInt(String.valueOf(maps1.get("value"))) == 2){
                    if (Boolean.parseBoolean(String.valueOf(maps1.get("checked")))){
                        options.setMustFill(1);
                    }else { options.setMustFill(0);}
                }
            }
            options.setOptionsContent(String.valueOf(jsonObject.get("content")));
            options.setSubjectId(subjectId);
            options.setOptionsId(Integer.parseInt(String.valueOf(jsonObject.get("id"))));
            count++;
            options.setOptionsType(count);
            int j = optionsMapper.insert(options);
            if (j < 1) {
                throw new RuntimeException("插入失败");
            }
//            try {
//                Thread.sleep(1000)  ;
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
        }
        // 将打包的编辑选项转化为map
        ObjectMapper objectMapper1 = new ObjectMapper();
        // JSON字符串转换成JSON大数组
        JSONArray jsonBigArray1 = JSON.parseArray(groupingArray);
        for (int i = 0; i < jsonBigArray1.size(); i ++){
            JSONObject jsonObject1 = jsonBigArray1.getJSONObject(i);
            List<String> list = objectMapper1.readValue(String.valueOf(jsonObject1.get("optionData")), new TypeReference<List<String>>() {});
            for(String list1 : list){
                UpdateWrapper<Options> wrapper = new UpdateWrapper<>();
                wrapper.eq("options_content",list1)
                                .set("group_name",jsonObject1.get("content"))
                                .set("group_id",jsonObject1.get("id"));
                int s = optionsMapper.update(null, wrapper);
                if (s < 1){
                    throw new RuntimeException("插入失败");
                }
            }

        }

        QueryWrapper<AllQuestion> wrapperSubjectId = new QueryWrapper<>();
        wrapperSubjectId.eq("subject_id",subjectId);
        if(allQuestionMapper.selectOne(wrapperSubjectId) != null){
            UpdateWrapper<AllQuestion> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("subject_id",subjectId)
                    .set("title",title);
            int wm = allQuestionMapper.update(null, updateWrapper);
            if (wm < 1){
                throw new RuntimeException("插入失败");
            }
            UpdateWrapper<DoubleChoiceQuestion> updateWrapper1 = new UpdateWrapper<>();
            updateWrapper1.eq("subject_id",subjectId)
                    .set("title",title);
            if(isGroup){
                updateWrapper1.set("is_group",1);
            }else  {updateWrapper1.set("is_group",0);}
            if(isSort){
                updateWrapper1.set("is_sort",1);
            }else  {updateWrapper1.set("is_sort",0);}
            if(isMustAnswer){
                updateWrapper1.set("is_must_answer",1);
            }else  {updateWrapper1.set("is_must_answer",0);}
            if(isWritePrompt){
                updateWrapper1.set("is_write_prompt",1);
            }else  {updateWrapper1.set("is_write_prompt",0);}
                    updateWrapper1.set("tip_content",tipContent)
                            .set("questions_jump_items",questionsJumpItems)
                            .set("number_of_options",numberOfOptions)
                            .set("most",most)
                            .set("mini",mini)
                            .set("grouping_array",groupingArray)
                            .set("option_array", optionArray);


            int k = doubleChoiceQuestionMapper.update(null, updateWrapper1);
            if (k < 0){
                throw new RuntimeException("插入失败");
            }
            return false;
        }
        //将题目数量（顺序）储存到对应的问题表和问卷表里面
        QueryWrapper<Questionnaire> wrapper = new QueryWrapper<>();
        wrapper.eq("formid",formid);
        Questionnaire questionnaire = questionnaireMapper.selectOne(wrapper);
        System.out.println(questionnaire);
        int questionNumber = questionnaire.getQuestionNumber();
        questionNumber++;

        UpdateWrapper<Questionnaire> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("formid", formid)
                .set("question_number", questionNumber);
        int k = questionnaireMapper.update(null, updateWrapper);
        if (k < 1){
            throw new RuntimeException("插入失败");
        }
        //将数据存进所有问题表里
        AllQuestion allQuestion = new AllQuestion();
        allQuestion.setFormid(formid);
        allQuestion.setQuestionType(questionType);
        allQuestion.setSubjectId(subjectId);
        allQuestion.setTitle(title);
        allQuestion.setSubjectNum(questionNumber);

        int i = allQuestionMapper.insert(allQuestion);
        if (i < 1) {
            throw new RuntimeException("插入失败");
        }

        //将数据存进多选题表里面
        DoubleChoiceQuestion doubleChoiceQuestion = new DoubleChoiceQuestion();
        doubleChoiceQuestion.setFormid(formid);
        doubleChoiceQuestion.setSubjectId(subjectId);
        doubleChoiceQuestion.setTitle(title);
        if(isGroup){
            doubleChoiceQuestion.setIsGroup(1);
        }else  { doubleChoiceQuestion.setIsGroup(0);}
        if(isSort){
            doubleChoiceQuestion.setIsSort(1);
        }else  {doubleChoiceQuestion.setIsSort(0);}
        if(isMustAnswer){
            doubleChoiceQuestion.setIsMustAnswer(1);
        }else  { doubleChoiceQuestion.setIsMustAnswer(0);}
        if(isWritePrompt){
            doubleChoiceQuestion.setIsWritePrompt(1);
        }else  { doubleChoiceQuestion.setIsWritePrompt(0);}
        doubleChoiceQuestion.setTipContent(tipContent);
        doubleChoiceQuestion.setQuestionsJumpItems(questionsJumpItems);
        doubleChoiceQuestion.setNumberOfOptions(numberOfOptions);
        doubleChoiceQuestion.setMost(most);
        doubleChoiceQuestion.setMini(mini);
        doubleChoiceQuestion.setGroupingArray(groupingArray);
        doubleChoiceQuestion.setOptionArray(optionArray);
        int l = doubleChoiceQuestionMapper.insert(doubleChoiceQuestion);
        if (l < 1) {
            throw new RuntimeException("插入失败");
        }

        return true;
    }

    @Override
    public boolean updateAddMultipleChoiceQuestion(String formid,String title,String subjectId,Boolean is_mustAnswer,Boolean is_writePrompt,String tipContent,String jumpingType,String questionsJumpItems,String numberOfOptions,String optionArray,String groupingArray,Boolean isGroup) throws IOException, InvocationTargetException, IllegalAccessException {
        int questionType = 1;
        QueryWrapper<Options> wrapper10 = new QueryWrapper<>();
        //对于增加功能 无伤大雅;对于新增功能，先清空选项表（选项更新数据具体到值比较麻烦）
        wrapper10.eq("subject_id", subjectId);
        optionsMapper.delete(wrapper10);
        ObjectMapper objectMapper = new ObjectMapper();
        // 将打包的编辑选项转化为map，并将optionArray先转为json，若是String类型，在没添加转义符号搞双引号的时候会将双引号省略从而无法解析出数据（已踩坑）
        JSONArray jsonBigArray = JSON.parseArray(optionArray);
        Options options = new Options();
        int count = 0;
        for (int k = 0; k < jsonBigArray.size(); k++) {
            String[] temp = {"IsScoring", "FillIn", "MustFill"};
            JSONObject jsonObject = jsonBigArray.getJSONObject(k);
            count++;
            Options tempOptions = new Options(subjectId, Integer.parseInt(String.valueOf(jsonObject.get("id"))), String.valueOf(jsonObject.get("content")), String.valueOf(jsonObject.get("nextTitleId")), count);
            List<Map<String, Object>> map = objectMapper.readValue(String.valueOf(jsonObject.get("moreUpdata")), new TypeReference<List<Map<String, Object>>>() {});
            for (Map maps : map) {// 仅做固定循环次数作用 故不需要用到
                int i = 0;
                Method[] methods = options.getClass().getMethods();
                // 通过反射 动态为options对象赋值
                for (Map maps1 : map) {
                    for (Method method : methods) {
                        if (("set" + temp[i]).equalsIgnoreCase(method.getName())) {
                            // 比较全小写 防止因为大小写问题产生歧义
                            method.invoke(options, (Optional.ofNullable(maps1.get(temp[i])).map(Boolean.class::cast).orElse(false).equals(true)) ? 1 : 0);
                        }
                    }
                    i++;
                }
                //System.out.println(options);
                //System.out.println(tempOptions);
            }
            options = tempOptions;
            //防止之前设置的其他值失效
            if (optionsMapper.insert(options) < 1) {
                throw new RuntimeException("插入失败");
            }
//            try {
//                Thread.sleep(1000)  ;
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
        }
        // 将打包的编辑选项转化为map
        ObjectMapper objectMapper1 = new ObjectMapper();
        // JSON字符串转换成JSON大数组
        JSONArray jsonBigArray1 = JSON.parseArray(groupingArray);
        for (int i = 0; i < jsonBigArray1.size(); i ++){
            JSONObject jsonObject1 = jsonBigArray1.getJSONObject(i);
            List<String> list = objectMapper1.readValue(String.valueOf(jsonObject1.get("optionData")), new TypeReference<List<String>>() {});
            for(String list1 : list){
                UpdateWrapper<Options> wrapper = new UpdateWrapper<>();
                wrapper.eq("options_content",list1)
                        .set("group_name",jsonObject1.get("content"))
                        .set("group_id",jsonObject1.get("id"));
                int s = optionsMapper.update(null, wrapper);
                if (s < 1){
                    throw new RuntimeException("插入失败");
                }
            }
        }
        //将题目数量（顺序）储存到对应的问题表和问卷表里面
        QueryWrapper<Questionnaire> wrapper = new QueryWrapper<>();
        wrapper.eq("formid", formid);
        formid = formid.trim();
        Questionnaire questionnaire = questionnaireMapper.selectOne(wrapper);
        int questionNumber = questionnaire.getQuestionNumber();
        questionNumber ++;
        UpdateWrapper<Questionnaire> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("formid", formid)
                .set("question_number", questionNumber);
        if (questionnaireMapper.update(null, updateWrapper) < 1) {
            throw new RuntimeException("插入失败");
        }
        //将数据存进所有问题表里
        QueryWrapper<AllQuestion> wrapperSubjectId = new QueryWrapper<>();
        wrapperSubjectId.eq("subject_id", subjectId);
        UpdateWrapper<MultipleChoiceQuestion> updateW = new UpdateWrapper<>();
        updateW.eq("subject_id", subjectId);

        if (allQuestionMapper.selectOne(wrapperSubjectId) != null) {
            // 对单选题 进行物理删除再更新（逻辑删除也可）
            UpdateWrapper<AllQuestion> updateWr = new UpdateWrapper<>();
            updateWr.eq("subject_id", subjectId).set("title", title);
            if (allQuestionMapper.update(null, updateWr) < 1) {
                throw new RuntimeException("插入失败");
            }
            multipleChoiceQuestionMapper.deleteBySubjectId(subjectId);
            MultipleChoiceQuestion multipleChoiceQuestion1 = new MultipleChoiceQuestion(formid, title, subjectId, (is_mustAnswer ? 1 : 0), (is_writePrompt ? 1 : 0), tipContent, groupingArray, optionArray, numberOfOptions, jumpingType, questionsJumpItems, isGroup ? 1 : 0);
            multipleChoiceQuestion1.setQuestionType(1);

            multipleChoiceQuestionMapper.insert(multipleChoiceQuestion1);
        }
        else {
            AllQuestion allQuestion = new AllQuestion(formid, questionType, subjectId, title, questionNumber);
            if (allQuestionMapper.insert(allQuestion) < 1) {
                throw new RuntimeException("插入失败");
            }
            MultipleChoiceQuestion multipleChoiceQuestion2 = new MultipleChoiceQuestion(formid, title, subjectId, (is_mustAnswer ? 1 : 0), (is_writePrompt ? 1 : 0), tipContent, groupingArray, optionArray, numberOfOptions, jumpingType, questionsJumpItems, isGroup ? 1 : 0);
            multipleChoiceQuestion2.setQuestionType(1);
            if (multipleChoiceQuestionMapper.insert(multipleChoiceQuestion2) < 1) {
                throw new RuntimeException("插入失败");
            }
        }
        return true;
    }
    @Override
    public boolean DeleteQuestion(String formid, String subjectId) throws RException {
        //将题目数量储存到对应的问题表和问卷表里面
        QueryWrapper<Questionnaire> wrapper = new QueryWrapper<>();
        wrapper.eq("formid",formid);
        Questionnaire questionnaire = questionnaireMapper.selectOne(wrapper);
        int questionNumber = questionnaire.getQuestionNumber();
        questionNumber --;

        UpdateWrapper<Questionnaire> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("formid", formid)
                .set("question_number",questionNumber);
        int k = questionnaireMapper.update(null, updateWrapper);
        if (k < 1){
            throw new RuntimeException("更新question_number失败");
        }

        QueryWrapper<Options> wrapper8 = new QueryWrapper<>();//删除选项
        wrapper8.eq("subject_id",subjectId);
        int wmk = optionsMapper.delete(wrapper8);
        if (wmk < 0){
            throw new RuntimeException("删除选项失败");
        }

        //先判断题型，再根据问题id进行删除
        QueryWrapper<AllQuestion> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("subject_id",subjectId);
        AllQuestion allQuestion = allQuestionMapper.selectOne(wrapper1);
        //2023.09.04 找出subject_num
        int allQuestionsubjectNum = allQuestion.getSubjectNum();

        //将找到的subject_num更新为0
        QueryWrapper<AllQuestion> wrapper10 = new QueryWrapper<>();
        wrapper10.eq("subject_id",subjectId);
//        AllQuestion allQuestion1 = allQuestionMapper.selectOne(wrapper10);
        allQuestion.setSubjectNum(0);
        int i1 = allQuestionMapper.update(allQuestion, wrapper10);
        if (i1 < 1){
            throw new RException(ResponseCode.ERROR.getDesc(), ResponseCode.ERROR.getCode());
        }

        //2023.09.04 这里估计是想重排序，但这种方式是否有效？
        for(int i = allQuestionsubjectNum; i<questionNumber+1; i++){
            QueryWrapper<AllQuestion> wrapper11 = new QueryWrapper<>();
            wrapper11
                    .eq("formid", formid)
                    .eq("subject_num",i+1);
            AllQuestion allQuestion2 = allQuestionMapper.selectOne(wrapper11);
            allQuestion2.setSubjectNum(i);
            i1 = allQuestionMapper.update(allQuestion2, wrapper11);
            if (i1 < 1){
                throw new RException(ResponseCode.ERROR.getDesc(), ResponseCode.ERROR.getCode());
            }
        }


        //根据删除的题目类型，对相应的表格中题型设置进行删 除
        int questionType = allQuestion.getQuestionType();
        if(questionType == 1){
            QueryWrapper<MultipleChoiceQuestion> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("subject_id",subjectId);
            if(multipleChoiceQuestionMapper.delete(wrapper2) < 1){
                throw new RuntimeException("删除失败");
            }
        }
        if(questionType == 2){
            QueryWrapper<DoubleChoiceQuestion> wrapper3 = new QueryWrapper<>();
            wrapper3.eq("subject_id",subjectId);
            if(doubleChoiceQuestionMapper.delete(wrapper3) < 1){
                throw new RuntimeException("删除失败");
            }
        }
        if(questionType == 3){
            QueryWrapper<FillInQuestion> wrapper4 = new QueryWrapper<>();
            wrapper4.eq("subject_id",subjectId);
            if(fillInQuestionMapper.delete(wrapper4) < 1){
                throw new RuntimeException("删除失败");
            }
        }
        if(questionType == 4){
            QueryWrapper<ScoreQuestion> wrapper5 = new QueryWrapper<>();
            wrapper5.eq("subject_id",subjectId);
            if(scoreQuestionMapper.delete(wrapper5) < 1){
                throw new RuntimeException("删除失败");
            }
        }
        if(questionType == 5){
            QueryWrapper<EvaluateQuestion> wrapper6 = new QueryWrapper<>();
            wrapper6.eq("subject_id",subjectId);
            if(evaluateQuestionMapper.delete(wrapper6) < 1){
                throw new RuntimeException("删除失败");
            }
        }
        //最后删除问卷的题目
        int D = allQuestionMapper.delete(wrapper1);
        if (D < 1){
            throw new RuntimeException("删除失败");
        }

        //这里忘记了更新表questionnaire的question_number字段
        return true;
    }
}

